//
//  CAReturnGoodsListViewController.m
//  LNH
//
//  Created by twentylx on 2018/2/24.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "CAReturnGoodsListViewController.h"
#import "CAReturnGoodsListTableViewCell.h"
#import <MJRefresh/MJRefresh.h>
#import "CAReturnGoodsListApi.h"
#import "CAReturnGoodsDetailApi.h"
#import "ReturnGoodsDetailViewController.h"
#import "CAReturnGoodsDetailApi.h"

@interface CAReturnGoodsListViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSInteger _page;
}

@property (nonatomic, strong) NSMutableArray *orderArray;
@property (nonatomic, strong) UITableView *returnGoodsTableView;

@end

static NSString *CellIdentify = @"ReturnCell";

@implementation CAReturnGoodsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/// 初始化数据
- (void)lm_initialDefaultsForController {
    
}

/// 绑定 vm
- (void)lm_bindViewModelForController {
}

/// 创建视图
- (void)lm_createViewForController {
    [self.view setNeedsUpdateConstraints];
    
    [self.view addSubview:self.returnGoodsTableView];
}

/// 配置导航栏
- (void)lm_configNavigationForController {
    self.navigationItem.title = @"售后列表";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
}

#pragma mark layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
    
    [_returnGoodsTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark get & set
- (UITableView *) returnGoodsTableView {
    if (!_returnGoodsTableView) {
        _returnGoodsTableView = [UITableView new];
        _returnGoodsTableView.dataSource = self;
        _returnGoodsTableView.delegate = self;
        [_returnGoodsTableView setBackgroundColor: [UIColor whiteColor]];
        _returnGoodsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_returnGoodsTableView registerClass:[CAReturnGoodsListTableViewCell class] forCellReuseIdentifier:CellIdentify];
        _returnGoodsTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
        [_returnGoodsTableView.mj_header beginRefreshing];
        _returnGoodsTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _returnGoodsTableView;
}

#pragma mark private method
- (void) backAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void) refreshData {
    _page = 1;
    [self loadDataWithPage:_page];
}

-(void) loadMoreData {
    _page++;
    [self loadDataWithPage:_page];
}

-(void)  loadDataWithPage:(NSUInteger) page{
    
    CAReturnGoodsListApi *orderListApi = [[CAReturnGoodsListApi alloc] initWithPage:page];
    
    [orderListApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        CAReturnGoodsListApi *api = (CAReturnGoodsListApi *) request;
        NSLog(@"%@", api.responseObject[@"result"][@"data"]);
        if (page == 1 || self.orderArray == nil) {
            self.orderArray = [NSMutableArray arrayWithArray:api.responseObject[@"result"][@"data"]];
        } else {
            [self.orderArray addObjectsFromArray:api.responseObject[@"result"][@"data"]];
        }
        self.returnGoodsTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.returnGoodsTableView.bounds.size.width, 0.01f)];
        
        [self.returnGoodsTableView.mj_header endRefreshing];
        [self.returnGoodsTableView.mj_footer endRefreshing];
        [self.returnGoodsTableView reloadData];
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
        [self.returnGoodsTableView.mj_header endRefreshing];
        [self.returnGoodsTableView.mj_footer endRefreshing];
    }];
}

- (void) loadDetailWithOrderId:(NSString *)orderId {
    CAReturnGoodsDetailApi *returnGoodsDetailApi = [[CAReturnGoodsDetailApi alloc] initWithOrderId:orderId];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [returnGoodsDetailApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CAReturnGoodsDetailApi *api = (CAReturnGoodsDetailApi *) request;
        if (api.done) {
            NSLog(@"%@", api.responseObject);
            ReturnGoodsDetailViewController *returnDetailVC = [ReturnGoodsDetailViewController new];
            returnDetailVC.dict = api.responseObject[@"result"];
            returnDetailVC.status = [api.responseObject[@"result"][@"status"] integerValue];
            [self.navigationController pushViewController:returnDetailVC animated:YES];
        } else {
            [SVProgressHUD lm_displayErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _orderArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CAReturnGoodsListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify];
    NSDictionary *dict = _orderArray[indexPath.row];
    
    cell = [[CAReturnGoodsListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.orderNoLabel.text = [NSString stringWithFormat:@"订单编号：%@", dict[@"order_sn"]];
    cell.orderStatusLabel.text = dict[@"goods_status_text"];
    [cell.goodsImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, dict[@"goods_img"]]]];
    cell.goodsNameLabel.text = dict[@"goods_name"];
    cell.countLabel.text = [NSString stringWithFormat:@"x%@", dict[@"goods_number"]];
    
    UITapGestureRecognizer *detailGesture = [UITapGestureRecognizer new];
    [cell.goodsView addGestureRecognizer:detailGesture];
    [[detailGesture rac_gestureSignal] subscribeNext:^(id x) {
        [self loadDetailWithOrderId:[NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]]];
    }];
    
    NSArray *attrArray = dict[@"attr"];
    __block NSString *attrStr = @"";
    [attrArray enumerateObjectsUsingBlock:^(NSDictionary *attrDict, NSUInteger idx, BOOL * _Nonnull stop) {
        attrStr = [NSString stringWithFormat:@"%@ %@:%@", attrStr, attrDict[@"name"], attrDict[@"attr_value"]];
    }];
    cell.sizeLabel.text = attrStr;
    NSString *number = [NSString stringWithFormat:@"%ld", [dict[@"goods_number"] integerValue]];
    NSString *total = [NSString stringWithFormat:@"%.2f", [dict[@"goods_price"] floatValue] * [dict[@"goods_number"] integerValue]];
    cell.countLabel.text = [NSString stringWithFormat:@"x%@", number];
    cell.totalLabel.text = [NSString stringWithFormat:@"共%@件商品  合计：%@", number, total];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 180;
}

@end

